<script setup lang="ts">
  import { ref, computed } from 'vue'
  import { useRouter, useRoute } from 'vue-router'
  import type { MenuItem } from '@/config/menu'

  interface Props {
    item: MenuItem
  }

  const props = defineProps<Props>()
  const router = useRouter()
  const route = useRoute()
  const isExpanded = ref(false)

  const isActive = computed(() => {
    return (
      route.path === props.item.path ||
      (route.path.includes(props.item.path) && props.item.path !== '/')
    )
  })

  const hasChildren = computed(() => {
    return props.item.children && props.item.children.length > 0
  })

  const handleClick = async () => {
    if (hasChildren.value) {
      isExpanded.value = !isExpanded.value
    } else {
      await router.push(props.item.path)
    }
  }
</script>

<template>
  <div class="mb-6">
    <div
      @click="handleClick"
      class="w-full flex items-center text-left pl-4 h-[44px] leading-[44px] cursor-pointer rounded"
      :class="{ 'bg-[#0B5CFF]': isActive }"
    >
      <span class="icon icon-xl" :class="[item.icon, { active: isActive }]"></span>
      <span
        class="flex-1 ml-1 pingfang font-bold text-[#666D7A]"
        :class="{ '!text-[#FEFEFE]': isActive }"
        >{{ item.label }}</span
      >
    </div>

    <!-- 子菜单 -->
    <div v-if="hasChildren && isExpanded" class="ml-4 border-l border-gray-600">
      <div v-for="child in item.children" :key="child.key" class="pl-4">
        <div
          @click="router.push(child.path)"
          class="w-full flex items-center px-4 py-2 text-left hover:bg-gray-700 text-sm"
          :class="{ 'bg-gray-700': route.path === child.path }"
        >
          <span
            class="icon icon-sm"
            :class="[child.icon, { active: route.path === child.path }]"
          ></span>
          <span class="ml-3">{{ child.label }}</span>
        </div>
      </div>
    </div>
  </div>
</template>
